#!/usr/bin/env python3
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 10:35:30
# @LastEditTime: 2025-03-14 10:35:35
# @Description: 告警通知模块
###

import json
import logging
import requests
from typing import Dict, List, Optional
from datetime import datetime

class NotificationManager:
    """告警通知管理器"""
    
    def __init__(self, config: Dict):
        """初始化通知管理器
        
        Args:
            config: 通知配置
        """
        self.config = config
        self.lark_webhook = config.get('lark_webhook')
        self.telegram_bot_token = config.get('telegram_bot_token')
        self.telegram_chat_id = config.get('telegram_chat_id')
        self.dingtalk_webhook = config.get('dingtalk_webhook')
        
    def _send_lark_message(self, title: str, content: str) -> bool:
        """发送飞书消息
        
        Args:
            title: 消息标题
            content: 消息内容
        """
        if not self.lark_webhook:
            return False
            
        try:
            message = {
                "msg_type": "post",
                "content": {
                    "post": {
                        "zh_cn": {
                            "title": title,
                            "content": [[{
                                "tag": "text",
                                "text": content
                            }]]
                        }
                    }
                }
            }
            
            response = requests.post(
                self.lark_webhook,
                json=message,
                timeout=5
            )
            return response.status_code == 200
            
        except Exception as e:
            logging.error(f"发送飞书消息失败: {e}")
            return False
            
    def _send_telegram_message(self, content: str) -> bool:
        """发送Telegram消息
        
        Args:
            content: 消息内容
        """
        if not (self.telegram_bot_token and self.telegram_chat_id):
            return False
            
        try:
            api_url = f"https://api.telegram.org/bot{self.telegram_bot_token}/sendMessage"
            message = {
                "chat_id": self.telegram_chat_id,
                "text": content,
                "parse_mode": "HTML"
            }
            
            response = requests.post(
                api_url,
                json=message,
                timeout=5
            )
            return response.status_code == 200
            
        except Exception as e:
            logging.error(f"发送Telegram消息失败: {e}")
            return False
            
    def _send_dingtalk_message(self, title: str, content: str) -> bool:
        """发送钉钉消息
        
        Args:
            title: 消息标题
            content: 消息内容
        """
        if not self.dingtalk_webhook:
            return False
            
        try:
            message = {
                "msgtype": "markdown",
                "markdown": {
                    "title": title,
                    "text": f"### {title}\n{content}"
                }
            }
            
            response = requests.post(
                self.dingtalk_webhook,
                json=message,
                timeout=5
            )
            return response.status_code == 200
            
        except Exception as e:
            logging.error(f"发送钉钉消息失败: {e}")
            return False
            
    def send_alert(self, platform: str, alert_type: str, details: Dict) -> None:
        """发送告警通知
        
        Args:
            platform: 云平台名称
            alert_type: 告警类型
            details: 告警详情
        """
        # 格式化时间
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 构建告警标题
        title = f"【{platform}】{alert_type}告警"
        
        # 构建告警内容
        content = f"时间：{now}\n\n"
        
        # 添加资源信息
        if "resource_id" in details:
            content += f"资源ID：{details['resource_id']}\n"
        if "resource_name" in details:
            content += f"资源名称：{details['resource_name']}\n"
            
        # 添加指标信息
        if "metric" in details:
            content += f"告警指标：{details['metric']}\n"
        if "value" in details:
            content += f"当前值：{details['value']:.2f}%\n"
        if "threshold" in details:
            content += f"告警阈值：{details['threshold']}%\n"
            
        # 添加其他详情
        if "message" in details:
            content += f"\n详细信息：\n{details['message']}\n"
            
        # 发送到各个通知渠道
        sent = False
        
        # 发送飞书消息
        if self.lark_webhook:
            if self._send_lark_message(title, content):
                sent = True
                logging.info("已发送飞书告警通知")
                
        # 发送Telegram消息
        if self.telegram_bot_token and self.telegram_chat_id:
            if self._send_telegram_message(f"<b>{title}</b>\n\n{content}"):
                sent = True
                logging.info("已发送Telegram告警通知")
                
        # 发送钉钉消息
        if self.dingtalk_webhook:
            if self._send_dingtalk_message(title, content):
                sent = True
                logging.info("已发送钉钉告警通知")
                
        if not sent:
            logging.warning("没有配置任何通知渠道或所有通知发送失败")
